/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package SemanticSpace.words.tools;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 *
 * @author hgs
 */
public class WordTool {
   /**
     * @param word1 第1词汇的解释
     * @param word2 第2词汇的解释
     * @return 第1词汇和第2词汇之间的距离
     * 步骤： <br>
     * 1. 求坐标<br>
     * 2. 求距离<br>
     */
    public  float getDistance(Map<Integer, Integer> word1, Map<Integer, Integer> word2) {
        //1. 求坐标
        int coorSum1 = 0, coorSum2 = 0;
        //word1Ids中存放word1解释对应的词汇的id号；word2Ids中存放word2解释对应的词汇的id号；temSet存放word1Ids和word2Ids的交集
        Set word1Ids = new HashSet(), word2Ids = new HashSet(), temSet = new HashSet();
        Iterator<Entry<Integer, Integer>> wordIt1 = word1.entrySet().iterator();
        //求第1个词汇的坐标平方和


        while (wordIt1.hasNext()) {
            Entry<Integer, Integer> wordCoord = wordIt1.next();
            coorSum1 += Math.pow(wordCoord.getValue(), 2);
            word1Ids.add(wordCoord.getKey());
            temSet.add(wordCoord.getKey());


        } //求第2个词汇的坐标平方和
        Iterator<Entry<Integer, Integer>> wordIt2 = word2.entrySet().iterator();


        while (wordIt2.hasNext()) {
            Entry<Integer, Integer> wordCoord = wordIt2.next();
            coorSum2 += Math.pow(wordCoord.getValue(), 2);
            word2Ids.add(wordCoord.getKey());


        }
        wordIt1 = null;
        wordIt2 = null;
        //求出word1和word2的解释中词汇id的交集，并放在word1Ids中
        temSet.retainAll(word2Ids);
        //计算交集中的词汇的差的平方和
        Iterator<Integer> it = temSet.iterator();


        float distanceTem = 0;


        while (it.hasNext()) {
            Integer tem = it.next();
            distanceTem += word1.get(tem).floatValue() * word2.get(tem).floatValue();


        }
        distanceTem = (float) (distanceTem / Math.sqrt(coorSum1 * coorSum2));
        //System.out.println("=====" + distanceTem);
        return (float) Math.sqrt(2 - 2 * distanceTem);


    }

}
